﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.SafetyManagementEntity.Model;
using KingRoad.EPM.Web.Areas.SafetyConstruction.ViewModels;
using KingRoad.EPM.Web.Areas.SafetyConstruction.SafetyConstructionFramework.Common;

namespace KingRoad.EPM.Web.Areas.SafetyConstruction.Controllers
{
    /// <summary>
    /// 安全施工管理-日常检查 SafetyConstruction.ScmDailyCheck.DailyCheckList
    /// </summary>
    public class ScmDailyCheckController : BaseController
    {
        //
        // GET: /DailyCheck/

        /// <summary>
        /// 日常检查-列表
        /// </summary>
        /// <returns></returns>
        public ActionResult DailyCheckList(string pageName)
        {
            var model = new ScmDailycheckViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            model.TheDailycheckList = ScmDailycheckUIRule.GetDailycheckListForPage(ViewBag.pageNum, ViewBag.numPerPage, "Dc_TimeStamp", out totalRecord, " Dc_BeCheckedSection in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;

            //字典类型列表实体（日常检查类型）
            model.TheSafetyconstructiondicList = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("3BD8B4D5-1E2A-4042-8CB5-9B542B33DFF0");
            return String.IsNullOrEmpty(pageName) ? View(model) : View(pageName, model);
        }
        /// <summary>
        /// 日常检查-列表(分页提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SplitPage()
        {
            var model = new ScmDailycheckViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return DailyCheckList("DailyCheckList");
            ViewBag.iput_dname = Request.Form["iput_dname"];
            ViewBag.iput_bdname = Request.Form["iput_bdname"];
            ViewBag.iput_ispro = Request.Form["iput_ispro"];
            ViewBag.iput_timestart = Request.Form["iput_timestart"];
            ViewBag.iput_timeend = Request.Form["iput_timeend"];
            string sql = "  Dc_BeCheckedSection in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ")  ";
            if (ViewBag.iput_bdname != "")
                sql += " and Dc_BeCheckedDepName like '%" + ViewBag.iput_bdname + "%' ";
            if (ViewBag.iput_ispro != "-1")
                sql += " and Dc_IsPro = " + ViewBag.iput_ispro + " ";
            if (ViewBag.iput_timestart != "")
                sql += " and Dc_CheckTime>='" + ViewBag.iput_timestart + "' ";
            if (ViewBag.iput_timeend != "")
                sql += " and Dc_CheckTime<='" + ViewBag.iput_timeend + "' ";
            model.TheDailycheckList = ScmDailycheckUIRule.GetDailycheckListForPage(ViewBag.pageNum, ViewBag.numPerPage, "Dc_TimeStamp", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;

            //字典类型列表实体（日常检查类型）
            model.TheSafetyconstructiondicList = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("3BD8B4D5-1E2A-4042-8CB5-9B542B33DFF0");
            return View("DailyCheckList", model);
        }
        /// <summary>
        /// 日常检查-新增
        /// </summary>
        /// <returns></returns>
        public ActionResult DailyCheckAdd()
        {
            var model = new ScmDailycheckViewModel();
            model.TheDailycheckInfo = new ScmDailycheckInfo();
            model.TheDailycheckInfo.Dc_ID = Guid.NewGuid().ToString();
            model.TheDailycheckInfo.Dc_State = 0;
            model.TheDailycheckInfo.Dc_CheckTime = DateTime.Now;
            //当前登陆人信息
            model.TheDailycheckInfo.Dc_CheckDepID = GetLoginUserDepartmentId;
            model.TheDailycheckInfo.Dc_CheckDepName = GetLoginUserDepartmentName;
            model.TheDailycheckInfo.Dc_OperateUserID = GetLoginUserId;
            model.TheDailycheckInfo.Dc_OperateUserName = GetLoginUserRealName;

            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "否", Value = "false" });
            list.Add(new SelectListItem { Text = "是", Value = "true" });
            ViewBag.list = list;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.日常检查);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.日常检查;
            //附件
            var assisId = GenerateRandom();
            var assisIdRet = 0;
            CreateAssistId(ScmSafetyknowledgeUIRule, assisId, out assisIdRet);
            ViewBag.AssisId = assisIdRet;
            //字典类型列表实体（日常检查类型）
            model.TheSafetyconstructiondicList = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("3BD8B4D5-1E2A-4042-8CB5-9B542B33DFF0");
            return View(model);
        }
        /// <summary>
        /// 日常检查-新增(信息提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DailyCheckAdd(ScmDailycheckViewModel model)
        {
            var dInfo = model.TheDailycheckInfo;
            if (!dInfo.Dc_IsPro)
            {
                dInfo.Dc_BriefProblem = null;
                dInfo.Dc_DetailsProblem = null;
                dInfo.Dc_CorrectTime = null;
                dInfo.Dc_CorrectDemand = null;
            }
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                dInfo.Assist_ID = AssistID;
                ScmDailycheckUIRule.AddDailycheck(dInfo);
            });
            dynamic jsonReturn = new ExpandoObject();
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "添加成功",
                    navTabId = "SafetyConstruction.ScmDailyCheck.DailyCheckList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        /// <summary>
        /// 日常检查-修改
        /// </summary>
        /// <returns></returns>
        public ActionResult DailyCheckEdit(Guid id)
        {
            var model = new ScmDailycheckViewModel();
            model.TheDailycheckInfo = ScmDailycheckUIRule.GetDailycheckInfo(id);
            //当前登陆人信息
            model.TheDailycheckInfo.Dc_OperateUserID = GetLoginUserId;
            model.TheDailycheckInfo.Dc_OperateUserName = GetLoginUserRealName;

            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "否", Value = "false" });
            list.Add(new SelectListItem { Text = "是", Value = "true" });
            ViewBag.list = list;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.日常检查);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.日常检查;
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(model.TheDailycheckInfo.Assist_ID, "DailyCheck_Rules");//DailyCheck_Rules  BizType类型
            ViewBag.AssisId = model.TheDailycheckInfo.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
            //字典类型列表实体（日常检查类型）
            model.TheSafetyconstructiondicList = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("3BD8B4D5-1E2A-4042-8CB5-9B542B33DFF0");
            return View(model);
        }
        /// <summary>
        /// 日常检查-修改(信息提交)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DailyCheckEdit(ScmDailycheckViewModel model)
        {
            var dInfo = model.TheDailycheckInfo;
            if (!dInfo.Dc_IsPro)
            {
                dInfo.Dc_BriefProblem = null;
                dInfo.Dc_DetailsProblem = null;
                dInfo.Dc_CorrectTime = null;
                dInfo.Dc_CorrectDemand = null;
            }
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                dInfo.Assist_ID = AssistID;
                ScmDailycheckUIRule.EditDailycheck(dInfo);
            });
            dynamic jsonReturn = new ExpandoObject();
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "修改成功",
                    navTabId = "SafetyConstruction.ScmDailyCheck.DailyCheckList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "修改失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 日常检查-删除
        /// </summary>
        /// <returns></returns>
        public JsonResult DailyCheckDelete(string id)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                ScmDailycheckUIRule.DeleteDailycheck(id);
            });
            dynamic jsonReturn = new ExpandoObject();
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "SafetyConstruction.ScmDailyCheck.DailyCheckList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 日常检查-下发
        /// </summary>
        /// <returns></returns>
        public ActionResult DailyCheckApproval(Guid id)
        {
            var model = new ScmDailycheckViewModel();
            model.TheAuditInfo = new ScmAuditInfo();
            model.TheAuditInfo.A_ID = Guid.NewGuid().ToString();
            model.TheAuditInfo.A_PrimayID = id.ToString();
            model.TheAuditInfo.A_Time = DateTime.Now;
            model.TheAuditInfo.A_IsApproved = true;
            model.TheAuditInfo.A_State = 0;
            //TODO:当前登陆人信息
            model.TheAuditInfo.A_DepID = GetLoginUserDepartmentId;
            model.TheAuditInfo.A_DepName = GetLoginUserDepartmentName;
            model.TheAuditInfo.A_ManID = GetLoginUserId;
            model.TheAuditInfo.A_ManName = GetLoginUserRealName;
            //日常检查信息
            ScmDailycheckInfo dInfo = ScmDailycheckUIRule.GetDailycheckInfo(id);
            int type = Convert.ToInt32(dInfo.Dc_TypeCode);
            string text = "";
            if (type == 1)
                text = "通过(下发给施工单位)";
            if (type == 2)
                text = "通过(下发给驻地办)";
            if (type == 3)
                text = "通过(下发给中心试验室)";
            if (type == 4)
                text = "通过(下发给总监办)";

            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = text, Value = "true" });
            ViewBag.auList = list;
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.日常检查);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.日常检查;
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(dInfo.Assist_ID, "DailyCheck_Rules");//SafeKnowledge_Rules  BizType类型
            ViewBag.AssisId = dInfo.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
            return View(model);
        }
        /// <summary>
        /// 日常检查-下发(提交)
        /// </summary>
        /// <param name="model">日常检查审批model</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DailyCheckApproval(ScmDailycheckViewModel model)
        {
            var aInfo = model.TheAuditInfo;
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                //日常检查信息
                ScmDailycheckInfo dInfo = ScmDailycheckUIRule.GetDailycheckInfo(new Guid(aInfo.A_PrimayID));
                int type = Convert.ToInt32(dInfo.Dc_TypeCode);
                int state = 0;
                //施工单位
                if (type == 1)
                    state = 1;
                //驻地办
                if (type == 2)
                    state = 2;
                //中心试验室
                if (type == 3)
                    state = 2;
                //总监办
                if (type == 4)
                    state = 3;
                ScmAuditUIRule.AddAudit(aInfo, 1, state);
            //修改附件
                ScmDailycheckInfo sInfo = ScmDailycheckUIRule.GetDailycheckInfo(new Guid(aInfo.A_PrimayID));
                var AssistID = Convert.ToInt32(Request.Form["AssistID"]);
                sInfo.Assist_ID = AssistID;

                ScmDailycheckUIRule.EditDailycheck(sInfo);
            });
            dynamic jsonReturn = new ExpandoObject();
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "下发成功",
                    navTabId = "SafetyConstruction.ScmDailyCheck.DailyCheckList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "下发失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 日常检查-查看明细
        /// </summary>
        /// <returns></returns>
        public ActionResult DailyCheckDetail(Guid id)
        {
            var model = new ScmDailycheckViewModel();
            model.TheDailycheckInfo = ScmDailycheckUIRule.GetDailycheckInfo(id);
            model.TheAuditList = ScmAuditUIRule.GetAuditListByPID(id.ToString());
            //获取模块ID
            ViewBag.MoudleID = GetEntityByUrl(Models.PageURL.日常检查);
            //附件目录名
            ViewBag.DirWhere = Models.DirName.日常检查;
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(model.TheDailycheckInfo.Assist_ID, "DailyCheck_Rules");//SafeKnowledge_Rules  BizType类型
            ViewBag.AssisId = model.TheDailycheckInfo.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));

            return View(model);
        }

        /// <summary>
        /// 日常检查-当前审批状态流程图
        /// </summary>
        /// <returns></returns>
        public ActionResult DailyCheckApprovalProcess(string type, string state)
        {
            ViewBag.ImageLc = type + state;
            return View();
        }

        /// <summary>
        /// 日常检查-延长整改期限
        /// </summary>
        /// <returns></returns>
        public ActionResult DailyCheckExtendCorrectTerm(Guid id)
        {
            var model = new ScmDailycheckViewModel();
            model.TheDailycheckInfo = ScmDailycheckUIRule.GetDailycheckInfo(id);
            //当前登陆人信息
            model.TheDailycheckInfo.Dc_OperateUserID = GetLoginUserId;
            model.TheDailycheckInfo.Dc_OperateUserName = GetLoginUserRealName;
            return View(model);
        }

    }
}
